import Taro from '@tarojs/taro'
import config from '@/app.config'
const { tabBar } = config
/**
 * 路由跳转
 */
// query字符串化
const stringify = (obj: object) => {
  let str = ''
  for (var Key in obj) {
    str += Key + '=' + obj[Key] + '&'
  }
  return str.substring(0, str.length - 1)
}
// vue-router转换weapp-router
const parseUrl = (location) => {
  if (typeof location === 'string') return location
  const { path, query } = location
  if (!query) return path
  // 过滤非对象类型
  if (Object.prototype.toString.call(query) !== '[object Object]') return path
  let queryStr = stringify(query)
  return path + '?' + queryStr
}
// 判断是否为tabBar页面
const isTabPage = (url: string) => {
  // 无tabBar配置
  if (!tabBar) return false
  const { list } = tabBar
  url = url.substring(1)
  const index = list.findIndex(v => v.pagePath === url)
  return index >= 0
}
// 同vue.router.push
const push = (location, success?, fail?, complete?) => {
  const url = parseUrl(location)
  const params = { url, success, fail, complete }
  // 能跳tabBar的，跳tabBar页面
  if (isTabPage(url)) {
    Taro.switchTab(params)
    return
  }
  const pages = Taro.getCurrentPages()
  const index = pages.findIndex(v => url.indexOf(v.route) >= 0)
  // 当前页, 不跳
  if (index >= 0) {
    const delta = pages.length - 1 - index
    if (delta === 0) throw '当前页, 不跳'
  }
  // 满招损, 开启新的页面栈
  if (pages.length > 8) {
    Taro.reLaunch(params)
    return
  }
  Taro.navigateTo(params)
}
// 同vue.router.replace
const replace = (location, success?, fail?, complete?) => {
  const url = parseUrl(location)
  const params = { url, success, fail, complete }
  Taro.redirectTo(params)
}
// 同vue.router.go
const go = (delta: number) => {
  Taro.navigateBack({ delta })
}
// 同vue.router.back
const back = () => {
  Taro.navigateBack()
}
// 关闭所有页面，打开到应用内的某个页面
const reLaunch = (location, success?, fail?, complete?) => {
  const url = parseUrl(location)
  const params = { url, success, fail, complete }
  Taro.reLaunch(params)
}

const router = {
  push,
  replace,
  go,
  back,
  reLaunch
}

export default router
